<template>
  <el-dialog
    :visible.sync="isShow"
    :title="mode === 'edit' ? '编辑部门' : '新增部门'"
    width="500"
  >
    <el-form ref="form" label-width="100px" :model="form" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model.trim="form.name" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model.trim="form.code" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="form.manager" @focus="focusEvent">
          <el-option
            v-for="(i, index) in userList"
            :key="index"
            :label="i.username"
            :value="i.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model.trim="form.introduce" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div style="text-align: center">
        <el-button @click="isShow = false">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { sysUserSimple } from '@/api/user'
import { companyDepartmentPost, companyDepartmentPut } from '@/api/departments'
export default {
  props: {
    initList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      isShow: false,
      userList: [],
      itemId: '',
      oldvalue: '',
      mode: 'add', // add 时新增弹框 edit 编辑弹框
      form: {
        code: '', //	string	非必须		部门编码，同级部门不可重复
        introduce: '', //	string	非必须		介绍
        manager: '', //	string	非必须		负责人名称
        name: '', //	string	非必须		部门名称
        pid: '' //	string	非必须		父级部门ID
      },
      rules: {
        name: [
          { required: true, message: '必填', trigger: 'change' },
          {
            validator: (rule, value, callblck) => {
              // 赛选出同样的名字 通过id
              // console.log(this.initList)
              let temp = ''
              // 新增
              if (this.mode === 'add') {
                temp = this.initList.filter((item) => {
                  return item.pid === this.itemId.id
                })
              } else {
                // 编辑
                temp = this.initList.filter((item) => {
                  return (
                    item.pid === this.itemId.pid && item.id !== this.itemId.id
                  )
                })
              }
              temp.some((item) => {
                return item.name === value.trim() && item.code === value
              })
                ? callblck(new Error('不能输入重复的部门名称：' + value))
                : callblck()
            },
            trigger: 'change'
          }
        ],
        code: [
          { required: true, message: '必填', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              // 部门编码自定义验证
              let result = ''
              // 新增
              if (this.mode === 'add') {
                result = this.initList.some((item) => {
                  return item.code === value
                })
              } else {
                // 编辑
                result = this.initList.some((item) => {
                  return item.code === value && item.id !== this.itemId.id
                })
                result
                  ? callback(new Error('不能输入重复的部门编码：' + value))
                  : callback()
              }
            }
          }
        ],
        introduce: [
          { required: true, message: '必填', trigger: 'change' },
          {
            max: 30,
            message: '30字内简单介绍下部门',
            trigger: 'change'
          }
        ],
        manager: [{ required: true, message: '必填', trigger: 'change' }]
      }
    }
  },
  watch: {
    isShow: {
      handler(newVal) {
        if (!newVal) {
          // 1 还原表单数据为初次渲染时的值 2 清除表单验证（他是异步处理nextTick）
          this.$refs.form.resetFields()
          // 关闭弹框时还原数据
          this.form = {
            code: '',
            introduce: '',
            manager: '',
            name: '',
            pid: ''
          }
        }
      }
    }
  },
  mounted() {
    // bus传值
    this.$bus.$on('show', (bol, item, mode) => {
      this.isShow = bol
      this.itemId = item // 当前项item
      this.mode = mode //
      console.log(item.id)
      // 深拷贝数据
      if (mode === 'edit') {
        // this.form = JSON.parse(JSON.stringify(item))
        this.form = { ...item }
        // this.form = item
      }
    })
  },
  beforeDestroy() {
    this.$bus.$off('show')
  },
  methods: {
    async focusEvent() {
      // 获取员工简单信息 通过length判断是否需要调用接口
      if (this.userList.length === 0) {
        const res = await sysUserSimple()
        this.userList = res.data
        // console.log(res)
      }
    },
    // 点击提交
    submit() {
      this.$refs.form.validate(async(result) => {
        if (result) {
          if (this.mode === 'add') {
            // 新增
            this.form.pid = this.itemId.id
            await companyDepartmentPost(this.form)
          } else {
            // 编辑
            this.oldvalue = { ...this.form }
            if (this.oldvalue !== this.form) {
              await companyDepartmentPut(this.form)
            }
          }
          this.$message.success(this.mode === 'add' ? '新增成功' : '编辑成功')
          this.isShow = false
          this.$emit('getData')
        }
      })
    }
  }
}
</script>

<style></style>
